package com.tlr.device.rest;

import static com.tfb.service.utility.JsonUtil.UTF8;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.tfb.service.utility.Utils;
import com.tlr.device.model.Result;

@Path("/bodymap")
public class PictureDownloadService {

    private static final Logger log = Logger.getLogger(DocumentFileService.class);

    @GET
    @Path("/download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response dowloadDocFile(@QueryParam("assessment") String assessmentid,@QueryParam("filename") String fileName) {
        try {
            // TODO
            File downloadFromDir = new File(AppContext.getFileUploadPath()+ "/" +assessmentid);
            File downloadFile = new File(downloadFromDir +"/"+ fileName);
            if (downloadFile.exists()) {
                return Response.ok().header("Content-Disposition",
                                            String.format("attachment; filename=%s;filename*=UTF-8''%s;filename=%s",
                                                          URLEncoder.encode(fileName, UTF8), URLEncoder.encode(fileName, UTF8), fileName))
                .header("Set-Cookie", "fileDownload=true; Path=/").entity(IOUtils.toByteArray(downloadFile.toURI())).build();
            } else {
                return Response.status(500).entity("路径不存在").build();
            }
        } catch (Exception ex) {
            log.error(Utils.getFullException(ex));
            return Response.status(500).entity("下载文件错误，请联系管理员").build();
        }
    }

    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<String>> listDocFiles(@QueryParam("assessment") String assessmentid) {
        File downloadFromDir = new File(AppContext.getFileUploadPath()+ "/" +assessmentid);
        if (downloadFromDir.exists()) {
            return new Result(0, "OK", downloadFromDir.list());
        } else {
            log.error("'" + AppContext.getDocDownloadDir() + "' 不存在！");
        }
        return new Result<>(500, "路径不存在!");
    }
}
